#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
const int N = 1010, M = 100010;
int n, m;
char g[N][N];
int vis[N][N], ans[M];

void dfs(int x, int y, int c, int i) {
	if (x<1 || x>n || y<1 || y>n || vis[x][y] != -1 ||
		g[x][y] - '0' != c) return;
	vis[x][y] = i;
	ans[i]++;
	dfs(x - 1, y, !c, i);
	dfs(x + 1, y, !c, i);
	dfs(x, y - 1, !c, i);
	dfs(x, y + 1, !c, i);
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			cin >> g[i][j];
		}
	}
	memset(vis, -1, sizeof vis);
	for (int i = 1; i <= m; i++) {
		int x, y; cin >> x >> y;
		if (vis[x][y] == -1) {
			dfs(x, y, g[x][y] - '0', i);
		}
		else ans[i] = ans[vis[x][y]];
	}
	for (int i = 1; i <= m; i++) cout << ans[i] << endl;
	return 0;
}